<?php


namespace app\controller\admin;


use app\BaseController;
use app\models\coupon\CouponModel;
use app\models\coupon\UserCouponModel;
use app\models\goods\GoodsModel;
use app\models\user\UserModel;
use app\services\order\CouponService;
use app\validate\CouponValidate;
use think\facade\Db;

class CouponController extends BaseController
{
    public function getGoodsArr()
    {
        try {
            $list = GoodsModel::where('status', 1)
                ->field('id,name,sell_price')
                ->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getList()
    {
        try {
            $where = [];
            $name = $this->request->param('coupon_name', '', 'trim');
            if ($name) {
                $where[] = ['coupon_name', '=', $name];
            }
            $status = $this->request->param('status', '', 'trim');
            if ($status != '') {
                $where[] = ['status', '=', $status];
            }
            $list = CouponModel::where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();

            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function add()
    {
        try {
            $couponName = $this->request->param('coupon_name', '', 'trim');
            $amount = $this->request->param('amount', '', 'trim');
            $startTime = $this->request->param('start_time', '', 'trim');
            $endTime = $this->request->param('end_time', '', 'trim');
            $sendType = $this->request->param('send_type', '', 'trim');
            $sendNum = $this->request->param('send_num', '', 'trim');
            $lessAmount = $this->request->param('less_amount', '', 'trim');
            $timeType = $this->request->param('use_coupon_type', '', 'trim');
            $useDay = $this->request->param('use_day', '', 'trim');
            $useStartTime = $this->request->param('use_start_time', '', 'trim');
            $useEndTime = $this->request->param('use_end_time', '', 'trim');
            $type = $this->request->param('type', '', 'trim');
            $limitType = $this->request->param('limit_type', '', 'trim');
            $limitNum1 = $this->request->param('limit_num1', '', 'trim');
            $limitNum2 = $this->request->param('limit_num2', '', 'trim');
            $userType = $this->request->param('use_type', '', 'trim');
            $typeId = $this->request->param('type_id', '', 'trim');
            $couponType = $this->request->param('coupon_type', '', 'trim');

            if (!$couponName) {
                throw new \Exception('请设置优惠券名称');
            }
            if (!$amount && $couponType != 2) {
                throw new \Exception('请设置优惠券金额');
            }
//            if (!$startTime || !$endTime) {
//                throw new \Exception('请设置优惠券发放时间');
//            }
            if (!$useDay && !$useStartTime && !$useEndTime) {
                throw new \Exception('请设置优惠券使用时间');
            }
            $limitNum = 0;
            if ($limitType == 1) {
                $limitNum = $limitNum1;
            }
            if ($limitType == 2) {
                $limitNum = $limitNum2;
            }
            $data = [
                'coupon_name' => $couponName,
                'start_time' => $startTime,
                'end_time' => $endTime,
                'amount' => $amount,
                'send_type' => $sendType,
                'send_num' => $sendNum,
                'residue_num' => $sendNum,
                'less_amount' => $lessAmount,
                'time_type' => $timeType,
                'use_day' => $useDay,
                'use_start_time' => $useStartTime,
                'use_end_time' => $useEndTime,
                'type' => $type,
                'limit_type' => $limitType,
                'limit_num' => $limitNum,
                'use_type' => $userType,
                'coupon_type' => $couponType,
                'type_id' => $userType == 0 ? '' : json_encode($typeId),
            ];
            $model = new CouponModel();
            $model->save($data);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function searchUser()
    {
        try {
            $keyword = $this->request->param('keyword');
            if (empty($keyword)) {
                return $this->success([]);
            }
            $userlist = UserModel::where('id|nick|mobile', 'like', '%' . $keyword . '%')->field('id,nick,mobile')->select();
            return $this->success($userlist);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function edit()
    {
        try {
            $couponName = $this->request->param('coupon_name', '', 'trim');
            $amount = $this->request->param('amount', '', 'trim');
            $startTime = $this->request->param('start_time', '', 'trim');
            $endTime = $this->request->param('end_time', '', 'trim');
            $sendType = $this->request->param('send_type', '', 'trim');
            $sendNum = $this->request->param('send_num', '', 'trim');
            $lessAmount = $this->request->param('less_amount', '', 'trim');
            $timeType = $this->request->param('use_coupon_type', '', 'trim');
            $useDay = $this->request->param('use_day', '', 'trim');
            $useStartTime = $this->request->param('use_start_time', '', 'trim');
            $useEndTime = $this->request->param('use_end_time', '', 'trim');
            $type = $this->request->param('type', '', 'trim');
            $limitType = $this->request->param('limit_type', '', 'trim');
            $limitNum1 = $this->request->param('limit_num1', '', 'trim');
            $limitNum2 = $this->request->param('limit_num2', '', 'trim');
            $userType = $this->request->param('use_type', '', 'trim');
            $typeId = $this->request->param('type_id', '', 'trim');
            $id = $this->request->param('id', '', 'trim');
            $couponType = $this->request->param('coupon_type', '', 'trim');
            if (!$id) {
                throw new \Exception('非法请求');
            }
            if (!$couponName) {
                throw new \Exception('请设置优惠券名称');
            }
            if (!$amount && $couponType != 2) {
                throw new \Exception('请设置优惠券金额');
            }
//            if (!$startTime || !$endTime) {
//                throw new \Exception('请设置优惠券发放时间');
//            }
            if (!$useDay && !$useStartTime && !$useEndTime) {
                throw new \Exception('请设置优惠券使用时间');
            }
            $limitNum = 0;
            if ($limitType == 1) {
                $limitNum = $limitNum1;
            }
            if ($limitType == 2) {
                $limitNum = $limitNum2;
            }
            $data = [
                'coupon_name' => $couponName,
                'start_time' => $startTime,
                'end_time' => $endTime,
                'amount' => $amount,
                'send_type' => $sendType,
                'send_num' => $sendNum,
                'residue_num' => $sendNum,
                'less_amount' => $lessAmount,
                'time_type' => $timeType,
                'use_day' => $useDay,
                'use_start_time' => $useStartTime,
                'use_end_time' => $useEndTime,
                'type' => $type,
                'limit_type' => $limitType,
                'limit_num' => $limitNum,
                'use_type' => $userType,
                'coupon_type' => $couponType,
                'type_id' => $userType == 0 ? '' : json_encode($typeId),
            ];
            $model = CouponModel::find($id);
            $model->save($data);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function statusChange()
    {
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('status');
            $info = CouponModel::find($id);
            $info->status = $status ? 0 : 1;
            $info->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function del()
    {
    }

    /**
     * 优惠券发放记录
     * @return \think\response\Json
     */
    public function record()
    {
        try {
            $where = [];
            $id = $this->request->param('id', '', 'trim');
            $where[] = ['coupon_id', '=', $id];
            $search = $this->request->param('search', '', 'trim');
            if ($search != '') {
                $userIdArr = UserModel::where('username|nick|mobile', 'like', '%' . $search . '%')->column('id');
                $where[] = ['user_id', 'in', $userIdArr];
            }
            $status = $this->request->param('status', '', 'trim');
            if ($status != '') {
                $where[] = ['is_used', '=', $status];
            }
            $list = UserCouponModel::where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $userInfo = UserModel::find($v['user_id']);
                $v['avatar'] = $userInfo['avatar'] ?? '';
                $v['nick'] = $userInfo['nick'] ?? '';
                $v['mobile'] = $userInfo['mobile'] ?? '';
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}